package com.eqxiu.ieditor.weixin.service;

import com.alibaba.fastjson.JSON;
import com.eqxiu.ieditor.weixin.api.MenuServiceApi;
import com.eqxiu.ieditor.weixin.dao.BottomMenuMapper;
import com.eqxiu.ieditor.weixin.dto.BottomMenuAttrDTO;
import com.eqxiu.ieditor.weixin.dto.BottomMenuDTO;
import com.eqxiu.ieditor.weixin.dto.BottomMenuReqDTO;
import com.eqxiu.ieditor.weixin.dto.MenuReqDTO;
import com.eqxiu.ieditor.weixin.model.BottomMenu;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class MenuServiceImpl implements MenuServiceApi {

	private Logger logger = LoggerFactory.getLogger(getClass().getName());

	private static final String MP_NAME = "易企秀";

	@Resource
	private BottomMenuMapper bottomMenuMapper;

	@Override
	public List<MenuReqDTO> findMutiMenuList(Integer mpId, Long firstMenu, Long secondMenu, Byte status) {
		List<MenuReqDTO> rtnList = new ArrayList<>(16);
		BottomMenu record = new BottomMenu();
		if (0L == firstMenu) {
			record.setUpperId(0L);
		} else {
			record.setId(firstMenu);
		}
		// 一级菜单
		List<BottomMenu> firstMenuList = bottomMenuMapper.findMenuList(record);
		if (firstMenuList.isEmpty()) {
			//没有查询到一级菜单
			logger.error("没有查询到一级菜单");
			return Collections.emptyList();
		}
		logger.info("一级菜单列表为：{}", firstMenuList);

		MenuReqDTO firstTemp = new MenuReqDTO();

		//一级菜单加入列表
        if (0 == secondMenu) {
            firstMenuList.forEach(item -> {
                try {
                    MenuReqDTO firstMenuDTO = (MenuReqDTO) firstTemp.clone();
                    firstMenuDTO.setId(item.getId())
                            .setMpName(MP_NAME)
                            .setFirstMenuName(item.getMenuName())
                            .setFirstSort(item.getSort())
                            .setAppid(item.getAppid())
                            .setPagePath(item.getPagePath())
                            .setType(item.getType())
                            .setStatus(item.getStatus())
                            .setUrl(item.getUrl())
                            .setCreateTime(item.getCreateTime())
                            .setUpdateTime(item.getUpdateTime());
                    rtnList.add(firstMenuDTO);
                } catch (CloneNotSupportedException e) {
                    logger.error("一级菜单克隆错误！", e);
                }
            });
        }

		MenuReqDTO secondTemp = new MenuReqDTO();

		//二级菜单加入列表
		firstMenuList.forEach(item -> {
			BottomMenu record2 = new BottomMenu();
			if (0 != status) {
				record2.setStatus(status);
			}
			if (0 == secondMenu) {
				record2.setUpperId(item.getId());
			} else {
				record2.setId(secondMenu);
			}
			List<BottomMenu> secondMenuList = bottomMenuMapper.findMenuList(record2);
			if (secondMenuList.isEmpty()) {
				return;
			}
            logger.info("二级级菜单列表为：{}", secondMenuList);
			// 遍历此一级菜单下所有的二级菜单
			secondMenuList.forEach(item2 -> {
				try {
					MenuReqDTO secondMenuDTO = (MenuReqDTO) secondTemp.clone();
					secondMenuDTO.setId(item2.getId())
                            .setMpName(MP_NAME)
							.setFirstMenuName(item.getMenuName())
							.setFirstSort(item.getSort())
							.setSecondMenuName(item2.getMenuName())
							.setSecondSort(item2.getSort())
							.setAppid(item2.getAppid())
							.setPagePath(item2.getPagePath())
							.setType(item2.getType())
							.setStatus(item2.getStatus())
							.setUrl(item2.getUrl())
							.setCreateTime(item2.getCreateTime())
							.setUpdateTime(item2.getUpdateTime());
					rtnList.add(secondMenuDTO);
				} catch (CloneNotSupportedException e) {
					logger.error("二级菜单克隆错误！", e);
				}
			});
		});
		logger.info("返回的return 列表为：{}", rtnList);
		return rtnList;
	}

	@Override
    public int mutiMenuListCount(Integer mpId, Long firstMenu, Long secondMenu, Byte status) {
        BottomMenu record = new BottomMenu();
        if (0 != status) {
            record.setStatus(status);
        }
        int count = 0;
        if (0 == secondMenu && 0 != firstMenu) {
            record.setUpperId(firstMenu);
            count += 1;
        } else if (0 != secondMenu && 0 != firstMenu) {
            record.setId(secondMenu);
        }
        count += bottomMenuMapper.mutiMenuListCount(record);
        return count;
    }

	@Override
	public List<BottomMenuDTO> findMenuList(BottomMenuDTO bottomMenuDTO) {
		BottomMenu bottomMenu = new BottomMenu();
		BeanUtils.copyProperties(bottomMenuDTO, bottomMenu);
		List<BottomMenu> menuList = bottomMenuMapper.findMenuList(bottomMenu);
		List<BottomMenuDTO> rtnList = new ArrayList<>(16);
		BottomMenuDTO temp = new BottomMenuDTO();
		menuList.forEach(item -> {
			try {
				BottomMenuDTO menuDTO = (BottomMenuDTO)temp.clone();
				BeanUtils.copyProperties(item, menuDTO);
				rtnList.add(menuDTO);
			} catch (Exception e) {
				logger.error("clone BottomMenuDTO 失败！", e);
			}
		});
		return rtnList;
	}

	@Override
	public MenuReqDTO getMenu(Long id) {

        MenuReqDTO menuReqDTO = new MenuReqDTO();
		BottomMenu menu = bottomMenuMapper.selectByPrimaryKey(id);
		if (null == menu) {
		    logger.error("未查询到此底部菜单，id={}", id);
		    return null;
        }
        BeanUtils.copyProperties(menu, menuReqDTO);
        // id为一级菜单的情况
        if (0 == menu.getUpperId()) {
            menuReqDTO.setFirstMenuName(menu.getMenuName());
            menuReqDTO.setFirstSort(menu.getSort());
            return menuReqDTO;
        }

        // id为二级菜单的情况，继续查询一级菜单
        BottomMenu firstMenu = bottomMenuMapper.selectByPrimaryKey(menu.getUpperId());
        menuReqDTO.setFirstMenuName(firstMenu.getMenuName());
        menuReqDTO.setFirstSort(firstMenu.getSort());
        menuReqDTO.setSecondMenuName(menu.getMenuName());
        menuReqDTO.setSecondSort(menu.getSort());
        return menuReqDTO;
	}

	@Override
	public int updateMenu(MenuReqDTO menuReqDTO) {
	    logger.info("进入updateMenu方法");

		BottomMenu menu = new BottomMenu();

		Long id = menuReqDTO.getId();
        BottomMenu bottomMenu = bottomMenuMapper.selectByPrimaryKey(id);

        // 一级菜单
        if (0 == bottomMenu.getUpperId()) {
            String firstMenuName = menuReqDTO.getFirstMenuName();
            List<BottomMenu> tempList = bottomMenuMapper.getMenuByName(firstMenuName);
            logger.info("tempList一级列表为:{}", tempList);
            if (!tempList.isEmpty() && !tempList.get(0).getId().equals(menuReqDTO.getId())) {
                logger.error("一级菜单名称与现有的菜单名称重复!");
                return -1;
            }
            BeanUtils.copyProperties(menuReqDTO, menu);
            menu.setMenuName(menuReqDTO.getFirstMenuName());
            menu.setSort(menuReqDTO.getFirstSort());
            menu.setUpdateTime(new Date());
			// 如果一级菜单的状态发生变化
			// 则先更新一级菜单下所有的二级菜单的状态
			if (!menuReqDTO.getStatus().equals(bottomMenu.getStatus())) {
                logger.info("======================");
				BottomMenuDTO dto = new BottomMenuDTO();
				dto.setId(id);
				dto.setStatus(menuReqDTO.getStatus());
				updateSubMenuList(dto);
			}
        } else {  // 二级菜单
            String secondMenuName = menuReqDTO.getSecondMenuName();
            List<BottomMenu> temp2List = bottomMenuMapper.getMenuByName(secondMenuName);
            logger.info("temp2List二级列表为:{}", temp2List);
            if (!temp2List.isEmpty() && !temp2List.get(0).getId().equals(menuReqDTO.getId())) {
                logger.error("二级菜单名称与现有的菜单名称重复!");
                return -2;
            }
            logger.info("以前的status={}, 要更新为：{}", bottomMenu.getStatus(), menuReqDTO.getStatus());
            if (1 == menuReqDTO.getStatus() && bottomMenu.getStatus() == -1) {
                BottomMenu first = new BottomMenu();
                first.setId(bottomMenu.getUpperId());
                first.setStatus((byte)1);
                first.setUpdateTime(new Date());
                logger.info("先先先更新一级菜单状态为：{}", first);
                bottomMenuMapper.updateByPrimaryKeySelective(first);
            }
			BeanUtils.copyProperties(menuReqDTO, menu);
			menu.setMenuName(menuReqDTO.getSecondMenuName());
			menu.setSort(menuReqDTO.getSecondSort());
			menu.setUpdateTime(new Date());
		}

		logger.info("更新的实体类为：{}", menu);
		return bottomMenuMapper.updateByPrimaryKeySelective(menu);
	}

	@Override
	public int save(MenuReqDTO menuReqDTO) {
		return 1;
//		BottomMenu menu = new BottomMenu();
//		// 一级菜单
//		if (StringUtils.isBlank(menuReqDTO.getSecondMenuName())) {
//			BottomMenu record = new BottomMenu();
//			record.setUpperId(0L);
//			List<BottomMenu> menuList = bottomMenuMapper.findMenuList(record);
//			if (menuList.size() > 3) {
//				// 最多3个一级菜单
//				logger.error("一级菜单不能超过3个");
//				return -1;
//			}
//			BeanUtils.copyProperties(menuReqDTO, menu);
//			menu.setUpperId(0L);
//			menu.setMenuName(menuReqDTO.getFirstMenuName());
//			menu.setSort(menuReqDTO.getFirstSort());
//			menu.setCreateTime(new Date());
//			menu.setUpdateTime(new Date());
//		} else {  // 二级菜单
//
//			BeanUtils.copyProperties(menuReqDTO, menu);
//			BottomMenu temp = bottomMenuMapper.getMenuByName(menuReqDTO.getFirstMenuName());
//			if (null == temp) {
//			    logger.error("一级菜单填写错误！");
//			    return -3;
//            }
//			menu.setUpperId(temp.getId());
//			BottomMenu record = new BottomMenu();
//			record.setUpperId(temp.getId());
//			List<BottomMenu> menuList = bottomMenuMapper.findMenuList(record);
//			if (menuList.size() > 5) {
//				// 最多5个一级菜单
//				logger.error("二级菜单不能超过5个");
//				return -2;
//			}
//			menu.setMenuName(menuReqDTO.getSecondMenuName());
//			menu.setSort(menuReqDTO.getSecondSort());
//			menu.setCreateTime(new Date());
//			menu.setUpdateTime(new Date());
//		}
//
//		logger.info("保存的实体为：{}", menu);
//
//		return bottomMenuMapper.insertSelective(menu);
	}

	@Override
	public void init(String buttonListString) {
	    logger.info("导入数据前先删除所有的老数据！");
        int delCount = bottomMenuMapper.deleteAll();
        logger.info("共删除了{}条数据", delCount);
        List<BottomMenuReqDTO> list = JSON.parseArray(buttonListString, BottomMenuReqDTO.class);
		for(int i=0; i<list.size(); i++) {
			BottomMenuReqDTO item1 = list.get(i);
			String name1 = item1.getName();
			BottomMenu menu1 = new BottomMenu();
			menu1.setMenuName(name1)
					.setStatus((byte)1)
					.setSort(i+1)
					.setUpperId(0L)
					.setCreateTime(new Date())
					.setUpdateTime(new Date());
			logger.info("++{}++:{}", i, new Gson().toJson(menu1));
			bottomMenuMapper.insertSelective(menu1);
			long menu1id = menu1.getId();
			List<BottomMenuAttrDTO> sub_button = item1.getSub_button();
			logger.info("$$sub_button$$={}", new Gson().toJson(sub_button));
			for (int j=0; j< sub_button.size(); j++) {
				BottomMenuAttrDTO item2 = sub_button.get(j);
				String name2 = item2.getName();
				String appid = item2.getAppid();
				String pagepath = item2.getPagepath();
				String typeString = item2.getType();
				String url = item2.getUrl();
				BottomMenu menu2 = new BottomMenu();
				menu2.setUpperId(menu1id)
						.setMenuName(name2)
						.setAppid(appid)
						.setPagePath(pagepath)
						.setType("view".equals(typeString)?(byte)1:2)
						.setUrl(url)
						.setSort(j+1)
						.setStatus((byte)1)
						.setCreateTime(new Date())
						.setUpdateTime(new Date());
				logger.info("=={}==:{}", j, new Gson().toJson(menu2));
				bottomMenuMapper.insertSelective(menu2);
			}
		}
	}

	@Override
    public int updateByPrimaryKeySelective(BottomMenuDTO dto) {
	    logger.info("进入updateByPrimaryKeySelective方法");
        BottomMenu bottomMenu = new BottomMenu();
	    BeanUtils.copyProperties(dto, bottomMenu);
	    bottomMenu.setUpdateTime(new Date());
	    bottomMenuMapper.updateByPrimaryKeySelective(bottomMenu);
		updateSubMenuList(dto);
		return 1;
    }

    private void updateSubMenuList(BottomMenuDTO dto) {
        logger.info("更新一级菜单下所有的子菜单的状态");
		long id = dto.getId();
		BottomMenu bottomMenu = bottomMenuMapper.selectByPrimaryKey(id);
		// 如果是二级菜单(并且是启用操作的时候),则启用对应的一级菜单
		if (0 != bottomMenu.getUpperId() && (dto.getStatus() == 1)) {
            BottomMenu updateFirst = new BottomMenu();
            updateFirst.setId(bottomMenu.getUpperId());
            updateFirst.setStatus(dto.getStatus());
            updateFirst.setUpdateTime(new Date());
            logger.info("更新一级为：{}", updateFirst);
            bottomMenuMapper.updateByPrimaryKeySelective(updateFirst);
			return;
		}
		// 如果是一级菜单，则更新他所有的子菜单
		BottomMenu record = new BottomMenu();
		record.setUpperId(id);
		record.setStatus(dto.getStatus());
		record.setUpdateTime(new Date());
		logger.info("更新食堂为：{}", record);
		bottomMenuMapper.updateStatusByUpperId(record);
	}


}
